package com.demo;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/*
可重入锁，比synchronized安全的是可以tryLock尝试获取锁，指定等待时间，超时则放弃，避免死锁
 */
class Demo8Counter {
    private final ReentrantLock lock = new ReentrantLock();

    // condition对象提供的wait、signal、signalAll方法实现synchronized代码块中的wait、notify、notifyAll功能，与Demo7类似就不演示了
    private final Condition condition = lock.newCondition();
    private int count = 0;
    public void add() {
        try {
            if (lock.tryLock(1, TimeUnit.SECONDS)) {
                this.count++;
//                condition.signalAll();
            }
        } catch (InterruptedException e) {
            lock.unlock();
        } finally {
            lock.unlock();
        }
    }
    public int get() {
//        condition.wait(2);
        return this.count;
    }
}

public class Demo8 {
    public static void main(String[] args) throws InterruptedException {
        Demo8Counter demo8Counter = new Demo8Counter();
        new Thread(() -> {
            demo8Counter.add();
        }).start();
        new Thread(() -> {
            demo8Counter.add();
        }).start();
        new Thread(() -> {
            demo8Counter.add();
        }).start();
        Thread.sleep(1000);
        System.out.println(demo8Counter.get());
    }
}
